// 底层调用语音识别返回
window.callbackVoiceXFData = function(dt) {
    $('.text-box')
        .find('h2')
        .html(dt);
    if (dt == '') {
        $('.text-box')
            .find('h2')
            .text(
                sessionStorage.languageSet == 'zh-CN' ?
                '请按下说话！' :
                'Please press to speak!'
            );
    } else {
        $.ajax({
            type: 'post',
            url: '/IoT/api/v3/Voice/VoiceString',
            data: JSON.stringify({
                dataString: dt,

                // 'userName': sessionStorage.userName,
                dataType: 1
            }),
            headers: {
                Authorization: window.sessionStorage.getItem('accessToken'),
                IamAccessToken: window.sessionStorage.getItem('iamAccessToken'),
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': ''
            },

            success: function(rt) {
                let result = rt.data;
                if (rt.code == 200) {
                    if (!result) {
                        $('.text-box')
                            .find('h2')
                            .text('软件没授权！');
                    } else {
                        result = result
                            .replace('已处理语音,内容', '')
                            .replace('---', '')
                            .replace('。', '');
                        let isInt = result.indexOf('未识别语音');
                        if (isInt != -1) {
                            $('.text-box')
                                .find('h2')
                                .html(
                                    result.replace('未识别语音,内容', '') +
                                    '未识别'
                                );
                        } else {
                            let contentTxt = result
                                .replace(/打/g, '')
                                .replace(/开/g, '');
                            if (
                                result.indexOf('打') != -1 ||
                                result.indexOf('开') != -1
                            ) {
                                $('.text-box')
                                    .find('h2')
                                    .html(contentTxt + '已经打开');
                            } else {
                                $('.text-box')
                                    .find('h2')
                                    .html(contentTxt + '已执行');
                            }
                        }
                    }
                } else {
                    $('.text-box')
                        .find('h2')
                        .html(rt.message);
                }
            },
            error: function(err) {
                $('.text-box')
                    .find('h2')
                    .html('System internal exception');
                console.log(err);
            }
        });
    }
};

// 处理字符串
window.handleString = function(str) {
    if (str) {
        var result = str;
        result = result
            .replace('已处理语音,内容', '')
            .replace('---', '')
            .replace('。', '');
    }
    return result || '';
};

// 微软语音识别返回
window.microsoftSpeech = function(dt) {
    callbackVoiceXFData(dt);
};

// key或者授权过期提示
window.voiceErrorAlert = function() {
    $('.voiceContainer')
        .find('h2 span')
        .text(
            sessionStorage.languageSet == 'zh-CN' ?
            'keys值错误或者授权过期' :
            'The keys value is wrong or the authorization has expired'
        );
    isVoices = false;
};

// 讯飞开始
window.StartVoiceXF = function() {
    try {
        myJavaFun.StartViceXF(parseInt(window.localStorage.XFOffline));
    } catch (ex) {}
};

// 安卓没有说话
window.callbackVoiceXFMessage = function(dt) {
    $('.text-box')
        .find('h2')
        .html(dt);

};

// 输入口令正确
window.VoicePasswords = function() {
    $('.voice-container').append(
        '<div class="pannel-chat-info">' +
        '<div class="chart-content"><span>口令正确</span></div>' +
        '</div>'
    );
    $('.voice-container').scrollTop($('.voice-container')[0].scrollHeight);
};

import IatTaste from './Voice'

export default {
    props: {
        selected: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            iconList: [
            {
                icon: 'icon_Tab_shouye_Initial',
                selectIcon: 'icon_Tab_shouye_Selected',
                img: require('../images/navigation_home.svg'),
                imgActive: require('../images/navigation_home_blue.svg'),
                page: 'home',
                title: '首页',
                route: '/index/home'
            },
            {
                icon: 'icon_Tab_shebeiliebiao_Initial',
                selectIcon: 'icon_Tab_shebeiliebiao_Selected',
                img: require('../images/navigation_equip.svg'),
                imgActive: require('../images/navigation_equip_blue.svg'),
                page: 'equipList',
                title: '设备',
                route: '/index/equipList?title=设备'
            },
            {
                isImg: true // 语音
            },
            {
                icon: 'icon_Tab_gongnengmokuai_Initial',
                selectIcon: 'icon_Tab_gongnengmokuai_Selected',
                img: require('../images/navigation_event.svg'),
                imgActive: require('../images/navigation_event_blue.svg'),
                page: 'modules',
                title: '事件',
                route: '/index/eventQuery?title=事件'
            },
            {
                icon: 'icon_Tab_shezhi_Initial',
                selectIcon: 'icon_Tab_shezhi_Selected',
                img: require('../images/navigation_setup.svg'),
                imgActive: require('../images/navigation_setup_blue.svg'),
                page: 'set',
                title: '设置',
                route: '/index/setpage?title=设置'
            }],
            selectedIndex: 0,
            showVoiceDialog: false,
            activeClass: '',
            setTime: '',
            isAPP: false,
            voiceConfig: {},
            iatTaste: null
        };
    },
    mounted() {
        this.selectedIndex = this.selected;

        try {
            console.log(myJavaFun);
            this.isAPP = true;
        } catch (error) {
            this.isAPP = false;
        }

        this.Axios.get('static/json/config.json').then((res) => {
            this.voiceConfig = res.data.voice;
            if (this.isAPP) {
                this.getLanguageChoice(this.voiceConfig.APP);
            } else {
                this.iatTaste = new IatTaste(this.voiceConfig.WEB);
                this.iatTaste.init();
            }
        }).catch(e => {
            this.$message({
                type: 'error',
                message: '获取语音识别配置失败!'
            });
        })
    },
    methods: {
        showVoice() {
            this.showVoiceDialog = true;
            try {
                myJavaFun.VoiceOpen();
            } catch (ex) {
                console.log('longin voiceopen error');
            }
        },
        closeVoice() {
            this.showVoiceDialog = false;
        },

        // 选择语言
        getLanguageChoice(config) {
            try {
                myJavaFun.SetKey(0, config.key); // （讯飞或者微软，KEY）
                myJavaFun.SetAIUILanguage(config.accent);
            } catch (ex) {
                console.log('longin SetKey error');
            }
        },
        onTouchStart() {
            if (this.setTime) clearTimeout(this.setTime);
            this.showVoice();
            this.$nextTick(() => {
                this.activeClass = 'active';
                $('.text-box')
                    .find('label,.title_1')
                    .addClass('displayNone')
                    .next('span')
                    .removeClass('displayNone');
                try {
                    myJavaFun.StartVoice('1');
                } catch (ex) {
                    this.iatTaste.init();
                    this.iatTaste.start();
                }
                this.orderFlag = true;
            });
        },
        onTouchEnd() {
            console.log(2);
            this.activeClass = '';
            let that = this;
            if (this.orderFlag) {
                this.orderFlag = false;

                $('.text-box')
                    .find('h2')
                    .removeClass('displayNone')
                    .html(that.$t('voice.tips.identifying'))
                    .next('span')
                    .addClass('displayNone');
                setTimeout(() => {
                    try {
                        myJavaFun.StopVoice();
                    } catch (ex) {
                        this.iatTaste.stop();
                        this.iatTaste.reset();
                        if (this.isAPP) {
                            $('.text-box')
                                .find('h2')
                                .removeClass('displayNone')
                                .html(that.$t('voice.tips.appOpen'))
                                .next('span')
                                .addClass('displayNone');
                        }
                    }
                }, 50);
            }
            this.setTime = setTimeout(() => {
                this.showVoiceDialog = false;
            }, 5000);
        },
        appBottomSelect(index, item) {
            if (index != 2 && index != this.selectedIndex) {
                this.selectedIndex = index;
                this.$router.push({ path: item.route });
            } else if (index == 2) {
                console.log('打开语音');
            }
        }
    }
};
